package com.gjxx.until;

import com.alibaba.fastjson2.JSONObject;
import com.gjxx.buss.domain.bean.TraceVo;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class GaoDeMapUtil {
    // 高德地图API的Key
    private static final String API_KEY = "96a253e688c5aa5a0b8a026cb667e61e";

    public static void main(String[] args) throws Exception {
        String longitude = "115.658755"; // 经度
        String latitude = "38.961134";   // 纬度
        String location = getLocationFromCoordinates(longitude, latitude);
        System.out.println(location);
    }
    public static String getLocationFromCoordinates(String longitude, String latitude) throws Exception {
        String url = "https://restapi.amap.com/v3/geocode/regeo?key=" + API_KEY + "&location=" + longitude + "," + latitude;
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        JSONObject jsonObject =  JSONObject.parseObject(response.toString());
        JSONObject regeocode = jsonObject.getJSONObject("regeocode");
        return regeocode.getString("formatted_address");
    }

    /**
     * 轨迹纠偏
     * @param paramStr
     * @return
     */
    public static String rectify(String paramStr) {
        String urlStr = "http://restapi.amap.com/v3/assistant/coordinate/convert?";
        String urlprm = "coordsys=gps&key="+API_KEY+"&locations=" + paramStr;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(urlprm.toString().getBytes("UTF-8"));
            os.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8"));
            String line;
            urlStr = "";
            while ((line = br.readLine()) != null) {
                urlStr += line;
            }
            br.close();
            JSONObject jsonObj = JSONObject.parseObject(urlStr);
            return (String)jsonObj.get("locations");
        }catch (Exception e){
            e.printStackTrace();
            log.error("轨迹纠偏失败:"+e.toString());
            return paramStr;
        }
    }

    /**
     * 轨迹纠偏
     */
    public static List<TraceVo> trajectoryRectify(List<TraceVo> list) {
        List<TraceVo> lvlist = new ArrayList<>();
        String listCorrection = "";
        try {
            if (list == null || list.size() == 0) {
                return null;
            } else {
                String paramStr = "";
                int count = list.size() / 500;
                for(int i = 0; i < count; i++){
                    for(int j = i * 500; j < (i + 1) * 500 ; j++){
                        paramStr += list.get(j).getLongitudeShow() + "," + list.get(j).getLatitudeShow() + ";";
                    }
                    listCorrection += rectify(paramStr)+";";
                    paramStr = "";
                }
                if(list.size() % 500 > 0){
                    for(int i = (count * 500); i < list.size(); i++){
                        paramStr += list.get(i).getLongitudeShow() + "," + list.get(i).getLatitudeShow() + ";";
                    }
                    listCorrection += rectify(paramStr)+";";
                }

                String[] arr = listCorrection.split(";");
                for (int i = 0; i < list.size(); i++) {
                    String correct = arr[i];
                    String[] gps = correct.split(",");
                    list.get(i).setLongitudeShow(new BigDecimal(gps[0]));
                    list.get(i).setLatitudeShow(new BigDecimal(gps[1]));
                }
                lvlist.addAll(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lvlist;
    }
}
